package com.yzw.login.controller;

import com.yzw.common.domain.EduAclPermission;
import com.yzw.common.domain.EduAclUser;
import com.yzw.common.dto.R;
import com.yzw.common.service.EduAclPermissionService;
import com.yzw.common.utils.JwtTokenUtil;
import com.yzw.common.vo.EduAclUserVo;
import com.yzw.common.service.impl.EduAclUserServiceImpl;
import com.yzw.common.vo.MenuVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Yzw
 * @Description TODO
 * @Date 2023/5/4 15:06
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class LoginController {
    @Resource
    private EduAclUserServiceImpl eduAclUserService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private EduAclPermissionService eduAclPermissionService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R login(@RequestBody EduAclUserVo eduAclUserVo) {
        Map<String,String> resultMap = new HashMap<>();
        String username = eduAclUserVo.getUsername();
        String password = eduAclUserVo.getPassword();

        UserDetails user = eduAclUserService.loadUserByUsername(username);

        if (null==user||!passwordEncoder.matches(password,user.getPassword())){
            return R.error("用户名或密码不正确");
        }
        if (!user.isEnabled()){
            return R.error("账号被禁用，请联系管理员！");
        }

        /**
         * 用户认证通过后，为了避免用户的每次操作都进行认证可将用户的信息保存在会话中。
         * spring security 提供会话管理，
         * 认证通过后将身份信息放入SecurityContextHolder上下文
         */
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token);
        //生成token
        String tokenStr = jwtTokenUtil.getToken(username);

        resultMap.put("token",tokenStr);
        return R.success("登录成功",resultMap);
    }

    @GetMapping("/info")
    public R info(String token) {
        String userName = jwtTokenUtil.getUserNameFromToken(token);
        EduAclUser user = eduAclUserService.loadUserByUsername(userName);
        List<MenuVo> menuVos = eduAclPermissionService.getById(user.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("roles", user.getRoles());
        map.put("name", user.getUsername());
        map.put("avatar",user.getSalt());
        map.put("menus",menuVos);
        return R.success("获取登录信息", map);
    }

    @ApiOperation("用户注销")
    @PostMapping("/logout")
    public R logout(HttpServletRequest request, HttpServletResponse response) {
        //将项目中的用户信息清空
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }
        return R.success("注销成功", null);
    }
}
